<template>
  <div>
    <van-nav-bar fixed placeholder safe-area-inset-top title="杨婷的账单统计" @click-left="back">
      <template #left>
        <van-icon name="arrow-left" size="18px" color="#333" />
      </template>
    </van-nav-bar>
    <div class="green">
      <div>
        <div @click="showDate = true">
          <span>{{ date }}</span>
          <van-icon name="calendar-o" style="vertical-align: middle;margin-left: 5px;" size="20px" />
        </div>
        <div>
          <span :class="[cur == 0 ? 'active' : '']" @click="goSearchExpenditure">支出</span>
          <span :class="[cur == 1 ? 'active' : '']" @click="goSearchIncome">收入</span>
        </div>
      </div>
      <div>
        <div v-show="cur == 0">共支出</div>
        <div v-show="cur == 1">共收入</div>
        <div>￥{{ money }}</div>
      </div>
    </div>
    <div class="title">
      <div v-show="cur == 0">支出构成</div>
      <div v-show="cur == 1">收入构成</div>
    </div>
    <div id="main" style="width: 100vw;height: 200px;"></div>
    <div class="title">
      每日对比
    </div>
    <div id="main2" style="width: 100vw;height: 300px;"></div>
    <div class="title">
      月度对比
    </div>
    <div id="main3" style="width: 100vw;height: 300px;"></div>
    <van-popup v-model="showDate" position="bottom" :style="{ height: '35%' }">
      <van-picker show-toolbar title="年月" visible-item-count="4" :columns="columns1" @confirm="onConfirm1"
        @cancel="onCancel1" />
    </van-popup>
  </div>
</template>

<script>
import { getTime } from "@/utils/publicMethods";

export default {
  data() {
    return {
      idb: '',
      money: 0,
      date: getTime('month'),
      cur: 0,
      showDate: false,
      columns1: [],
    }
  },
  mounted() {
    const _this = this
    _this.$store.dispatch('tools/setIdb').then(res => {
      _this.idb = res
      _this.getMoney()
      _this.getMonthCompare()
    })
    _this.updateDate()
  },
  watch: {
    cur() {
      this.getMonthCompare()
    }
  },
  methods: {
    weightlessnessReduction(arr, key) {
      for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          if (arr[i][key] == arr[j][key]) {
            arr[i].value += arr[j].value
            arr.splice(j, 1)
            j--
          }
        }
      }
      return arr
    },
    getMonthCompare() {
      const date = new Date()
      const year = date.getFullYear()
      let category=this.cur==0 ? '支出': '收入'
      this.idb.query({
        tableName: "account",
        condition: (item) => item.yearMonth.split('年')[0] == year && item.category==category,
        success: r => {
          let myChart = this.$echarts.init(document.getElementById('main3'))
          let xAxisData = []
          let seriesData = []
          let dayArr = []
          r.forEach(e => {
            dayArr.push({ time: e.yearMonth, value: +e.money })
          })
          let arr = this.weightlessnessReduction(dayArr,'time')
          arr.forEach(e => {
            xAxisData.push(e.time)
            seriesData.push(+e.value)
          })
          myChart.setOption({
            xAxis: {
              type: 'category',
              data: xAxisData
            },
            yAxis: {
              type: 'value'
            },
            tooltip: {
              trigger: 'item'
            },
            series: [
              {
                data: seriesData,
                type: 'bar',
                showBackground: true,
                label: {
                  show: true,
                  formatter: function (arg) {
                    return arg.data.value
                  }
                },
                backgroundStyle: {
                  color: 'rgba(180, 180, 180, 0.2)'
                }
              }
            ]
          })
        }
      });
    },
    getRevenueAndExpenditure(list) {
      let myChart = this.$echarts.init(document.getElementById('main2'))
      let xAxisData = []
      let seriesData = []
      let dayArr = []
      list.forEach(e => {
        dayArr.push({ time: e.time, value: +e.money })
      })
      let arr = this.weightlessnessReduction(dayArr, 'time')
      arr.forEach(e => {
        xAxisData.push(e.time)
        seriesData.push(+e.value)
      })
      myChart.setOption({
        xAxis: {
          type: 'category',
          data: xAxisData
        },
        yAxis: {
          type: 'value'
        },
        tooltip: {
          trigger: 'item'
        },
        series: [
          {
            data: seriesData,
            type: 'bar',
            showBackground: true,
            label: {
              show: true,
              formatter: function (arg) {
                return arg.data.value
              }
            },
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            }
          }
        ]
      })
    },
    getClassification(list) {
      let arr = []
      list.forEach(e => {
        let obj = { value: Number(e.money), name: e.industry }
        arr.push(obj)
      })
      arr = this.weightlessnessReduction(arr, 'name')
      return arr
    },
    getIndustry(list) {
      let myChart = this.$echarts.init(document.getElementById('main'))
      let data = []
      data = this.getClassification(list)
      myChart.setOption({
        tooltip: {
          trigger: 'item'
        },
        series: [
          {
            roseType: 'angle',
            name: '行业',
            type: 'pie',    // 设置图表类型为饼图
            radius: '55%',  // 饼图的半径，外半径为可视区尺寸（容器高宽中较小一项）的 55% 长度。
            data: data,
            label: {
              show: true,
              formatter: function (arg) {
                return arg.data.name + arg.data.value + ' 元 \n' +
                  arg.percent + '%'
              }
            },
            itemStyle: {
              normal: {
                shadowBlur: 200,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      })
    },
    getMoney() {
      const _this = this
      _this.money = 0
      _this.idb.query({
        tableName: "account",
        condition: (item) => item.yearMonth == _this.date,
        success: r => {
          let curList = []
          if (_this.cur == 0) {
            r.forEach(e => {
              if (e.category == '支出') {
                curList.push(e)
                _this.money += Number(e.money)
              }
            })
          } else {
            r.forEach(e => {
              if (e.category == '收入') {
                curList.push(e)
                _this.money += Number(e.money)
              }
            })
          }
          this.getIndustry(curList)
          this.getRevenueAndExpenditure(curList)
        }
      });
    },
    updateDate() {
      const date = new Date()
      const year = date.getFullYear()
      for (let i = 1; i < 13; i++) {
        this.columns1.push(`${year}年${i}月`)
      }
    },
    onCancel1() {
      this.showDate = false
    },
    onConfirm1(val) {
      const _this = this
      _this.date = val
      _this.showDate = false
      _this.getMoney()
    },
    goSearchExpenditure() {
      const _this = this
      _this.cur = 0
      _this.getMoney()
    },
    goSearchIncome() {
      const _this = this
      _this.cur = 1
      _this.getMoney()
    },
    back() {
      this.$router.go(-1)
    }
  },
}
</script>

<style lang="less" scoped>
.title {
  margin: 20px 15px;
}

.active {
  background-color: #ff976a !important;
  padding: 5px;
}

.green {
  background-color: #4CAF50;
  width: 100vw;
  height: 40vw;
  color: #fff;

  &>div:nth-child(2) {
    margin: 0 8vw;

    &>div:first-child,
    &>div:nth-child(2) {
      color: #ddd;
    }

    &>div:last-child {
      font-size: 25px;
      font-weight: bold;
      margin-top: 2.7vw;
    }
  }

  &>div:first-child {
    &>div:nth-child(2) {
      span {
        margin: 0 5px;
      }
    }

    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 10.67vw;
    margin: 0 8vw;
    margin-bottom: 5.3vw;
  }
}
</style>